import {HTTP} from '../utils/http'
var COS = require('cos-wx-sdk-v5');
var http = new HTTP()
function getCOSObjDir() {
  return http.request({
    url:'tencentCloud/getCosObjectDir',}
  );
}

function getCOSInfo() {
  return http.request({
    url:'tencentCloud/getCosInfo',}
  );
}
export async function uploadCOSTxCloud(pre, titleDir, path,size) {
  let Dir;
  let fileDir;
  console.log(path.split('//')[1]);
  // debugger;
  await getCOSObjDir().then(res => {
    Dir = res.data;
    fileDir = Dir[titleDir];
  }).catch(err => {
    console.error(err);
  });


  let COSInfo;
  let region;
  let bucketName;
  let secretId;
  let secretKey;

  await getCOSInfo().then(res => {
    COSInfo = res.data;
    region = COSInfo.region;
    bucketName = COSInfo.bucketName;
    secretId = COSInfo.secretId;
    secretKey = COSInfo.secretKey;
  }).catch(err => {
    console.error(err);
  });

  // 创建ObsClient实例
  let cosClient = new COS({
    SecretId: secretId,
    SecretKey: secretKey
  });

  let key;

  if (pre === '') {
    key = fileDir + '/' + path.split("//")[1];
  } else {
    key = fileDir + '/' + pre + '_' + path.split("//")[1];
  }

  return new Promise((resolve, reject) => {
    cosClient.postObject({
      Bucket: bucketName,
      Region: region,
      Key: key,
      FilePath: path,
    }, function(err, result) {
      if (err) {
        console.error('Error-->' + err);
        reject(err);
      } else {
        if (result.statusCode < 300) {
          console.log('Location-->' + result.Location);
          console.log('ETag-->' + result.ETag);
          let url = 'https://' + result.Location;
          resolve(url);
        } else {
          reject(err);
          console.log('Code-->' + result.CommonMsg.Code);
          console.log('Message-->' + result.CommonMsg.Message);
        }
      }
    });
  });

}